<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Menu;
use Symfony\Component\HttpKernel\Exception\HttpException;

class MenuController extends Controller
{

    protected function initialize()
    {
        $this->model = new Menu();
    }

    public function index()
    {
        $model = $this->model->all();

        return $this->success(data: buildTreeWithoutIds($model->toArray()));
    }

    public function store(Request $request)
    {
        $body = $request->json()->all();

        try {
            $this->model::create($body);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function show($id)
    {
        try {
            $model = $this->model::find($id);

            return $this->success(data: $model);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function update($id, Request $request)
    {
        $body = $request->json()->all();
        try {
            $this->model::where('id', $id)->update($body);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function destroy($id)
    {
        try {
            $this->model::destroy($id);
            return $this->success(data: null);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function flat()
    {
        $model = $this->model->all();
        return $this->success(data: $model->toArray());
    }

    public function permission() {

        $model = $this->model->all();

        return $this->success(data: buildTreeWithoutIds($model->toArray()));
    }
}
